package cn.liyicun.school.car2;

import java.sql.Connection;
import java.util.Base64;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.render.ViewType;
import com.jfinal.template.Engine;

import cn.liyicun.school.car2.controller.IndexController;
import cn.liyicun.school.car2.controller.driver.DriverRoutes;
import cn.liyicun.school.car2.controller.user.UserRoutes;
import cn.liyicun.school.car2.interceptor.ErrorActionInterceptor;
import cn.liyicun.school.car2.model._MappingKit;

public class Schoolcar2JfinalConfig extends JFinalConfig {

	private static Prop p = loadConfig();

	@Override
	public void configConstant(Constants arg0) {
		arg0.setDevMode(p.getBoolean("devMode", false));
		arg0.setViewType(ViewType.FREE_MARKER);
	}

	private static Prop loadConfig() {
		String config=System.getProperty("jfinal_config","dev");
		try {
			return PropKit.use(String.format("config_%s.properties",config));
		} catch (Exception e) {
			return PropKit.use("config_dev.properties");
		}
	}

	@Override
	public void configEngine(Engine arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void configHandler(Handlers arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void configInterceptor(Interceptors arg0) {
		arg0.addGlobalActionInterceptor(new ErrorActionInterceptor());

	}

	private WallFilter wallFilter;

	@Override
	public void configPlugin(Plugins me) {
		DruidPlugin druidPlugin = getDruidPlugin(p);
		wallFilter = new WallFilter();
		wallFilter.setDbType("mysql");
		druidPlugin.addFilter(wallFilter);
		druidPlugin.addFilter(new StatFilter());
		me.add(druidPlugin);
		ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
		arp.setTransactionLevel(Connection.TRANSACTION_READ_COMMITTED);
		_MappingKit.mapping(arp);

		arp.setPrimaryKey("line_place_rela", "line_id,place_id");
		me.add(arp);
		if (p.getBoolean("devMode", false)) {
			arp.setShowSql(true);
		}
	}

	public static DruidPlugin getDruidPlugin(Prop p) {
		return new DruidPlugin(p.get("jdbcUrl"), p.get("user"),
				new String(Base64.getDecoder().decode(p.get("password").trim())));
	}

	@Override
	public void configRoute(Routes arg0) {

		arg0.add(new UserRoutes());
		arg0.add(new DriverRoutes());
		arg0.add("/", IndexController.class, "_view");

	}

	public static void main(String[] args) {
		JFinal.start("src/main/webapp", 8081, "/", 5);

	}

}
